package cn.dubito.seller.service;

import cn.dubito.api.ProductRpc;
import cn.dubito.api.domain.ProductRpcParam;
import cn.dubito.entity.Product;
import cn.dubito.entity.enums.ProductStatusEnum;
import com.hazelcast.core.HazelcastInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author liliang
 * @description: hazelcast 缓存相关
 * @date 2018/5/28.
 */
@Component
public class ProductCache {

    private static Logger LOG = LoggerFactory.getLogger(ProductCache.class);

    /**
     * 缓存名称
     */
    public static final String CACHE_NAME = "dubito_product";

    @Autowired
    private ProductRpc productRpc;

    @Autowired
    private HazelcastInstance hazelcastInstance;


    /**
     * 读取缓存
     *
     * @param id ID
     */
    @Cacheable(cacheNames = CACHE_NAME)
    public Product readCache(String id) {
        LOG.info("RPC 查询单个产品请求参数:{}", id);
        Product result = productRpc.findById(id);
        LOG.info("RPC 查询单个产品,结果:{}", result);
        return result;
    }

    /**
     * 更新缓存
     *
     * @param product product 指定key
     * @return product
     */
    @CachePut(cacheNames = CACHE_NAME, key = "#product.id")
    public Product putCache(Product product) {
        return product;
    }

    /**
     * 删除缓存数据
     *
     * @param id
     */
    @CacheEvict(cacheNames = CACHE_NAME)
    public void removeCache(String id) {
    }

    /**
     * 读取缓存全部数据
     *
     * @return list
     */
    public List<Product> readAllCache() {
        Map map = hazelcastInstance.getMap(CACHE_NAME);
        List<Product> productList = null;
        if (map != null && map.size() > 0) {
            productList = new ArrayList<>();
            productList.addAll(map.values());
        } else {
            productList = findAll();
        }
        return productList;
    }


    public List<Product> findAll() {
        ProductRpcParam param = new ProductRpcParam();
        List<String> status = new ArrayList<>();
        status.add(ProductStatusEnum.IN_SELL.name());
        param.setStatusList(status);

        LOG.info("查询全部产品参数:{}", param);

        List<Product> result = productRpc.query(param);

        LOG.info("查询全部产品返回结果: {}", result);
        return result;
    }

}
